//
//  RFChoice3ViewController.m
//  HeadYang
//
//  Created by sunmingming on 15/8/4.
//  Copyright (c) 2015年 xiaoluoli. All rights reserved.
//

#import "RFChoice3ViewController.h"
#import "DDViewController.h"

@interface RFChoice3ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,weak) IBOutlet UITableView *listView;
@property(nonatomic,strong) NSMutableArray *barberArray;


@end

@implementation RFChoice3ViewController

@synthesize listView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"选择产品";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.barberArray = [NSMutableArray array];
    [self getGoods];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.barberArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    inde = @"RFGoodsID";
    cell = [tableView dequeueReusableCellWithIdentifier:inde];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RFGoods" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSDictionary *barDic = [self.barberArray objectAtIndex:indexPath.row];
    UIImageView *logoIMG = (UIImageView*)[cell viewWithTag:99];
    UIButton *lab1 = (UIButton*)[cell viewWithTag:1];
    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
    UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
    [lab1 setTitle:[NSString stringWithFormat:@"%i",indexPath.row] forState:UIControlStateDisabled];
//    [lab1 addTarget:self action:@selector(goodsDetailPressed:) forControlEvents:UIControlEventTouchUpInside];
    lab2.text = [NSString stringWithFormat:@"%@ %@",[tooles replaceNullFromDic:barDic withKeyArray:@[@"brand"]],[tooles replaceNullFromDic:barDic withKeyArray:@[@"name"]]];
    lab3.text = [NSString stringWithFormat:@"%.2f元,%@,%@,%@,%@",
                 [[barDic valueForKey:@"price"] floatValue],
                 [tooles replaceNullFromDic:barDic withKeyArray:@[@"gender"]],
                 [tooles replaceNullFromDic:barDic withKeyArray:@[@"permType"]],
                 [tooles replaceNullFromDic:barDic withKeyArray:@[@"hairType"]],
                 [tooles replaceNullFromDic:barDic withKeyArray:@[@"stage"]]
                 ];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *barDic = [self.barberArray objectAtIndex:indexPath.row];
    APPALL.goodsDic = barDic;
    [self createOrder];
}

-(void)goodsDetailPressed{
    return;
}

-(void)createOrder{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateFormatter stringFromDate:APPALL.selectDate];
    NSString *couponStr = APPALL.couponDic?[APPALL.couponDic valueForKey:@"couponNum"]:@"";
    NSDictionary *para =
    @{@"date":dateStr,
      @"barber":[APPALL.barberDetailDic valueForKey:@"id"],
      @"startTimePiece":[NSString stringWithFormat:@"%i",APPALL.startTimeFlag],
      //      @"gender":@"",
      //      @"hairType":@"",
      @"coupon":couponStr,
      @"memo":@"",
      @"expected":@"100",
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_create" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    APPALL.orderDetailDic = [aSucData valueForKey:@"order"];
                    [self addService];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

-(void)addService{
    NSMutableArray *goodArray = [NSMutableArray array];
    for(int i = 0; i <= 4; i++){
        if(self.barberArray.count >= i + 1){
            NSDictionary *barDic = [self.barberArray objectAtIndex:i];
            [goodArray addObject:[barDic valueForKey:@"id"]];
        }else{
            [goodArray addObject:@""];
        }
    }
    NSDictionary *para =
    @{@"id":[APPALL.orderDetailDic valueForKey:@"id"],
      @"type":[NSString stringWithFormat:@"%i",APPALL.myType],
      @"postAddress":@"",
      @"goods1":[goodArray objectAtIndex:0],
      @"goods2":[goodArray objectAtIndex:1],
      @"goods3":[goodArray objectAtIndex:2],
      @"goods4":[goodArray objectAtIndex:3],
      @"goods5":[goodArray objectAtIndex:4],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_service" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    DDViewController *vc = [DDViewController new];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

-(void)getGoods{
    NSDictionary *para;
    NSString *avURL;
    
    switch (APPALL.myType) {
        case hairTangFa:{
            para =
            @{@"owner":[APPALL.barberStoreDic valueForKey:@"id"],
              @"brand":@"",
              @"isSuit":@"yes",
              @"pricem":@"",
              @"pricex":@"",
              @"gender":APPALL.myGender,
              @"hairNature":@"",
              @"hairType":APPALL.myHairType,
              @"useTimes":@"",
              @"permType":APPALL.rfType,
              @"stage":@"",
              @"token":APPALL.myUserItem.token};
            avURL = @"goods_perm";
        }
            break;
        case hairRanFa:{
            para =
            @{@"owner":[APPALL.barberStoreDic valueForKey:@"id"],
              @"brand":@"",
              @"isSuit":@"yes",
              @"pricem":@"",
              @"pricex":@"",
              @"gender":APPALL.myGender,
              @"hairNature":@"",
              @"hairType":APPALL.myHairType,
              @"useTimes":@"",
              @"dyeType":APPALL.rfType,
              @"color":@"",
              @"contain":@"",
              @"token":APPALL.myUserItem.token};
            avURL = @"goods_dye";
        }
            break;
        case hairHuli:{
            para =
            @{@"owner":[APPALL.barberStoreDic valueForKey:@"id"],
              @"brand":@"",
              @"isSuit":@"yes",
              @"pricem":@"",
              @"pricex":@"",
              @"gender":APPALL.myGender,
              @"hairNature":@"",
              @"hairType":APPALL.myHairType,
              @"useTimes":@"",
              @"careType":APPALL.rfType,
              @"token":APPALL.myUserItem.token};
            avURL = @"goods_care";
        }
            break;
        default:
            break;
    }
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:avURL withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    [_barberArray removeAllObjects];
                    NSArray *cityArray = [aSucData objectForKey:@"goods"];
                    for (NSDictionary *dic in cityArray) {
                        [_barberArray addObject:dic];
                    }
                    [self.listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

@end